const bcrypt = require('bcryptjs');

module.exports = {
  async checkTable(app, name) {
    try {
      // 获取所有表名
      const tables = await app.model.queryInterface.showAllTables();

      // 检查表是否存在
      if (!tables.includes(`${name}s`)) {
        await app.model.sync({ force: false });
        console.log('模型同步完成');
      }
    } catch (error) {
      console.error('检查表或同步模型时出错:', error);
    }
  },
  errHandler(ctx, error, code, message) {
    ctx.status = code;

    ctx.body = {
      code,
      message,
      error,
    };
  },
  successHandler(ctx, result, code = 200) {
    ctx.status = code;

    ctx.body = {
      code,
      message: 'ok',
      result,
    };
  },
  getPagination(page_num = 1, page_size = 10) {
    const offset = (page_num - 1) * page_size;

    const limit = +page_size;

    return {
      offset,
      limit,
    };
  },
  // 生成密码哈希
  async hash(password) {
    const saltRounds = 10; // 盐值复杂度，数值越高越安全但越耗时
    return await bcrypt.hash(password, saltRounds);
  },
  // 验证密码
  async compare(password, hash) {
    return await bcrypt.compare(password, hash);
  },
};
